package logic

import (
	"context"
	"encoding/json"

	"diff.wang/asynqsrv/clientrpc/internal/svc"
	"diff.wang/asynqsrv/clientrpc/pb"
	"diff.wang/asynqsrv/common"

	"github.com/hibiken/asynq"
	"github.com/zeromicro/go-zero/core/logx"
)

type EmailLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewEmailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EmailLogic {
	return &EmailLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

//  邮件分发 实时
func (l *EmailLogic) Email(in *pb.EmailReq) (*pb.EmailResp, error) {
	// todo: add your logic here and delete this line
	payload, err := json.Marshal(common.EmailDeliveryPayload{
		UserId:     int(in.UserId),
		TemplateId: in.TemplateId,
	})
	if err != nil {
		return nil, err
	}
	task := asynq.NewTask(common.MsgEmailDelivery, payload)
	// 立即处理
	ti, err := l.svcCtx.AsynqClient.Enqueue(task, asynq.MaxRetry(int(in.Retry)))
	if err != nil {
		return nil, err
	}
	logx.Info("push email queue success, %+v", ti)

	return &pb.EmailResp{
		Tag: true,
	}, nil
}
